import os.path
import re
import requests
import urllib3
from lxml import etree



class SendRequest:
    """基本请求模板，待完善"""
    urllib3.disable_warnings()
    def __init__(self):
        self.ABS_PATH = os.path.abspath(os.path.dirname(__file__))
        self.url = ''
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36'
        }
        self.cookies = {}  # cookie设置
        self.data = {}  # 表单数据
        self.page = 1  # 翻页控制参数
        self.session = requests.session()
        # self.movie = '测试'
        # print(f'{self.ABS_PATH}/{self.movie}(临时文件)/{self.movie}.m3u8')
        # print(f'{self.ABS_PATH}/{self.movie}/{self.movie}.mp4')

    @property
    def UGetRequest(self):
        response = self.session.get(url=self.url, headers=self.headers, cookies=self.cookies, verify=False)
        return response

    @UGetRequest.setter
    def UGetRequest(self, kwargs: dict):
        if kwargs.get('url'):
            self.url = kwargs.get('url')
        if kwargs.get('referer'):
            self.headers['referer'] = kwargs.get('referer')

    @property
    def UPostRequest(self):
        response = self.session.post(url=self.url, headers=self.headers, cookies=self.cookies, data=self.data,
                                     verify=False)
        return response

    @UPostRequest.setter
    def UPostRequest(self, kwargs: dict):
        if kwargs.get('url'):
            self.url = kwargs.get('url')
        if kwargs.get('referer'):
            self.headers['referer'] = kwargs.get('referer')


class MeiJu99(SendRequest):
    def __init__(self):
        super().__init__()

    def synthesis(self):
        """合成视频"""
        if not os.path.exists(self.movie):
            os.mkdir(self.movie)
        cmd = f'ffmpeg.exe -f concat -safe 0 -i {self.ABS_PATH}\\{self.movie}(临时文件)\\{self.movie}.m3u8 -c copy {self.ABS_PATH}\\{self.movie}\\{self.movie}.mp4'
        os.system(cmd)

    def download_mvs(self, total_mv_urls):
        """下载所有片段"""
        if not os.path.exists(self.movie+'(临时文件)'):
            os.mkdir(self.movie+'(临时文件)')
        num = 1
        # 按照ffmpeg的格式将ts文件的路径写入到一个m3u8文件之中用于合成视频
        new_m3u8_file = open(self.movie+'(临时文件)'+'/'+self.movie+'.m3u8', 'a', encoding='utf-8')
        for url in total_mv_urls:
            self.UGetRequest = {'url': url}
            res = self.UGetRequest
            with open(self.movie+'(临时文件)'+'/'+str(num)+'.ts', 'wb')as f:
                f.write(res.content)
                new_m3u8_file.write("file '%s\%s\%d.ts'" % (self.ABS_PATH, self.movie+'(临时文件)', num))
                new_m3u8_file.write('\n')
                print(str(num) + '下载成功')
                num+=1
            if num == 201:
                break
        new_m3u8_file.close()
        self.synthesis()

    def play_page(self, play_pages_url):
        """播放页面提取下载链接"""
        self.UGetRequest = {'url': play_pages_url}
        response = self.UGetRequest
        text_html = response.content.decode()
        with open('playpage.html', 'w', encoding='utf-8')as f:
            f.write(text_html)
        m3u8_url = re.findall('var next="(.*?)";var prePage=', text_html)[0]    # 提取播放页面中的m3u8文件的地址
        self.UGetRequest = {'url': m3u8_url}
        m3u8_file = self.UGetRequest.content
        with open('1.m3u8', 'wb')as f:
            f.write(m3u8_file)
        # 请求上方获取到的m3u8_url以获取存放了ts地址的m3u8
        last_m3u8_url = m3u8_url.split('/2')[0] + re.search('/\d+/\w+/[\d+kb/]*\w+/index\.m3u8', m3u8_file.decode()).group()
        self.UGetRequest = {'url': last_m3u8_url}
        response = self.UGetRequest.content.decode()
        # 解析并保存所有的ts地址
        total_mv_urls = [m3u8_url.split('/2')[0]+i for i in re.findall('/\d+/\w+/\d+\w+/hls/\w+\.ts', response)]
        self.download_mvs(total_mv_urls)

    def index(self, index_url):
        """电影详情页面"""
        self.UGetRequest = {'url': index_url}
        response = self.UGetRequest
        text_html = response.content.decode()
        with open('index.html', 'w', encoding='utf-8')as f:
            f.write(text_html)
        tree = etree.HTML(text_html)
        using_lines = tree.xpath('//*[@id="playTab"]/div[1]/ul//li//text()')    # 可使用线路(名称)
        play_tab = tree.xpath('//*[@id="playTab"]/div')     # 下载线路
        mv_information = ''.join(tree.xpath('//*[@id="zanpian-score"]/ul//text()'))     # 电影信息
        status = ''.join(tree.xpath('//*[@id="zanpian-score"]/ul/li[2]//text()'))
        if '完结' not in status:
            numbers_sets = ''.join(re.findall('集数：共(.*?)集 每集\d+分钟|状态：更新至(.*?)集', mv_information)[0])
            for i, tab in zip(range(len(using_lines)), play_tab[1:]):
                tab_num = len(tab.xpath('./ul/li'))
                if tab_num == int(numbers_sets):
                    print('%d.' % (i+1), using_lines[i]+'(可用)', end='\t')
                else:
                    print('%d.' % (i+1), using_lines[i]+'(不可用)', end='\t')
        else:
            for i, tab in zip(range(len(using_lines)), play_tab[1:]):
                print('%d.' % (i + 1), using_lines[i], end='\t')
        print()
        download_num = int(input('请选择下载线路(输入编号):'))
        play_pages_urls = ['https://www.99meijutt.com'+i for i in play_tab[download_num].xpath('./ul//li/a/@href')]
        for play_pages_url in play_pages_urls:
            self.play_page(play_pages_url)
            break

    def search(self):
        """搜索页面采集"""
        titles = []
        self.UPostRequest = {'url': 'https://www.99meijutt.com/search.php'}
        self.data['searchword'] = input('请输入影片关键字或主演名:')
        response = self.UPostRequest
        text_html = response.content.decode()
        with open('search.html', 'w', encoding='utf-8') as f:
            f.write(text_html)
        tree = etree.HTML(text_html)
        div_lst = tree.xpath('//*[@id="content"]/div')
        print('搜索到的电影如下:')
        for i, div in zip(range(1, len(div_lst)), div_lst):  # 遍历数组与div列表为标题设置编号
            title = div.xpath('./div[1]/a/@title')[0]
            if i % 2 != 0 and i != len(div_lst)-1:
                print(str(i) + '.' + title, end='\t\t')
            else:
                print(str(i) + '.' + title)
            titles.append(title)
        num = int(input('请输入您要下载的电影序号:'))
        self.movie = titles[num-1]
        index_url = 'https://www.99meijutt.com' + div_lst[num-1].xpath('./div[1]/a/@href')[0]
        self.index(index_url)


if __name__ == '__main__':
    mj = MeiJu99()
    mj.search()
